{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://pptwinpics.oss-cn-beijing.aliyuncs.com/CDA%E8%AE%B2%E5%B8%88%E6%B0%B4%E5%8D%B0_20200314161940.png)\n",
    "# Python 新人的快速入门教程 \n",
    "\n",
    " 大家好，我是 CDA 曹鑫。\n",
    "\n",
    "**课程代码请访问我的 Github：**[Github 项目库](https://github.com/imcda/Python-Tutorial-for-Humans/blob/master/001-Python%20%E6%95%99%E7%A8%8B%E7%AE%80%E4%BB%8B/002-%E8%A7%81%E8%AF%86%E4%B8%80%E4%B8%8B%20Python.ipynb)\n",
    "\n",
    " **学数据科学，上 [CDA.cn](http://cda.cn)**\n",
    " \n",
    " 让我们开始学习吧！\n",
    "\n",
    "## 目录\n",
    "\n",
    "\n",
    "1. [Imports](#1.-Imports)\n",
    "2. [Data Types](#2.-Data-Types)\n",
    "3. [Math](#3.-Math)\n",
    "4. [Comparisons and Boolean Operations](#4.-Comparisons-and-Boolean-Operations)\n",
    "5. [Lists](#5.-Lists)\n",
    "6. [Dictionaries](#6.-Dictionaries)\n",
    "7. [Strings](#7.-Strings)\n",
    "8. [Conditional Statements](#8.-Conditional-Statements)\n",
    "9. [For Loops and While Loops](#9.-For-Loops-and-While-Loops)\n",
    "10. [Tuples](#10.-Tuples)\n",
    "11. [Sets](#11.-Sets)\n",
    "12. [Defining Functions](#12.-Defining-Functions)\n",
    "13. [Anonymous Functions](#13.-Anonymous-Functions) \n",
    "14. [Comprehensions](#14.-Comprehensions)\n",
    "15. [Map and Filter](#15.-Map-and-Filter)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Imports\n",
    "> 导入\n",
    "\n",
    "如果你看过《奇异博士》这部电影，就可以联想到法师们将魔法封印到武器中，在战斗中可以快速释放魔法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 'generic import' of math module（导入数学模块的一般方式）\n",
    "import math\n",
    "math.sqrt(25)  # 开平方根"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__doc__',\n",
       " '__file__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " 'acos',\n",
       " 'acosh',\n",
       " 'asin',\n",
       " 'asinh',\n",
       " 'atan',\n",
       " 'atan2',\n",
       " 'atanh',\n",
       " 'ceil',\n",
       " 'copysign',\n",
       " 'cos',\n",
       " 'cosh',\n",
       " 'degrees',\n",
       " 'e',\n",
       " 'erf',\n",
       " 'erfc',\n",
       " 'exp',\n",
       " 'expm1',\n",
       " 'fabs',\n",
       " 'factorial',\n",
       " 'floor',\n",
       " 'fmod',\n",
       " 'frexp',\n",
       " 'fsum',\n",
       " 'gamma',\n",
       " 'gcd',\n",
       " 'hypot',\n",
       " 'inf',\n",
       " 'isclose',\n",
       " 'isfinite',\n",
       " 'isinf',\n",
       " 'isnan',\n",
       " 'ldexp',\n",
       " 'lgamma',\n",
       " 'log',\n",
       " 'log10',\n",
       " 'log1p',\n",
       " 'log2',\n",
       " 'modf',\n",
       " 'nan',\n",
       " 'pi',\n",
       " 'pow',\n",
       " 'radians',\n",
       " 'remainder',\n",
       " 'sin',\n",
       " 'sinh',\n",
       " 'sqrt',\n",
       " 'tan',\n",
       " 'tanh',\n",
       " 'tau',\n",
       " 'trunc']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 列出包中所有的函数\n",
    "dir(math)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# import a function（导入一个函数）\n",
    "from math import sqrt\n",
    "sqrt(25)    # no longer have to reference the module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cos(3) :  -0.4480736161291701\n",
      "cos(-3) :  -0.9899924966004454\n",
      "cos(0) :  1.0\n",
      "cos(math.pi) :  -1.0\n",
      "cos(2*math.pi) :  1.0\n",
      "math.floor(-45.17) :  -46\n",
      "math.floor(100.12) :  100\n",
      "math.floor(100.72) :  100\n",
      "math.floor(math.pi) :  3\n"
     ]
    }
   ],
   "source": [
    "# import multiple functions at once（一次导入等多个函数）\n",
    "from math import cos, sin, floor\n",
    "\n",
    "# cos （cos() 返回x的弧度的余弦值。）\n",
    "print(\"cos(3) : \",  math.cos(90))\n",
    "print(\"cos(-3) : \",  math.cos(-3))\n",
    "print(\"cos(0) : \",  math.cos(0))\n",
    "print(\"cos(math.pi) : \",  math.cos(math.pi))\n",
    "print(\"cos(2*math.pi) : \",  math.cos(2*math.pi))\n",
    "\n",
    "# floor （向下取整）\n",
    "print (\"math.floor(-45.17) : \", math.floor(-45.17))\n",
    "print (\"math.floor(100.12) : \", math.floor(100.12))\n",
    "print (\"math.floor(100.72) : \", math.floor(100.72))\n",
    "print (\"math.floor(math.pi) : \", math.floor(math.pi))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import all functions in a module (generally discouraged)（导入模块里的所有函数功能）\n",
    "from math import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define an alias（定义一个别名）\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Data Types\n",
    "> 数据类型\n",
    "\n",
    "2.1 确定对象的类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "int"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(2)         # returns 'int'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "float"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(2.0)       # returns 'float'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type('two')     # returns 'str'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "bool"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(True)      # returns 'bool'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "NoneType"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(None)      # returns 'NoneType'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2.2 检查对象是否为给定类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance(2.0, int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance(2.0, (int, float))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2.3 将对象转换为给定类型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "float(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "int(2.9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2.9'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(2.9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2.4 零、`None`和空值都会被转化成`False`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool(None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool('')    # empty string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool([])    # empty list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool({})    # empty dictionary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2.5 非空值和不为零的都会被转化成`True`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool('two')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bool([2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Math\n",
    "> 算术"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "10 + 4    # add（加）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "10 - 4    # subtract（减）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "40"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "10 * 4    # multiply（乘）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10000"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "10 ** 4    # exponent（指数）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.5"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "10 / 4     # divide（除）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "7 % 3      # modulo（取余数） - computes the remainder（计算余数）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "10 // 4    # Floor division（取整除） - 向下取接近除数的整数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Comparisons and Boolean Operations\n",
    "> 比较运算和布尔运算"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4.1 赋值语句（Assignment statement）:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4.2 比较运算（Comparisons）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x == 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x > 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x >= 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x != 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4.3 布尔运算（Boolean operations）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "5 > 3 and 6 > 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "5 > 3 or 5 < 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "not False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "False or not False and True     # evaluation order: not, and, or"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://pptwinpics.oss-cn-beijing.aliyuncs.com/CDA%E8%AE%B2%E5%B8%88%E6%B0%B4%E5%8D%B0_20200314161940.png)\n",
    "## 5. Lists\n",
    "> 列表\n",
    "\n",
    "列表属性：有序，可迭代，可变，可以包含多种数据类型\n",
    "\n",
    "创建一个空列表的2种方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create an empty list (two ways)\n",
    "empty_list = []\n",
    "empty_list = list()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a list\n",
    "simpsons = ['homer', 'marge', 'bart']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "检查列表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'homer'"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 打印出第 0 个元素\n",
    "simpsons[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(simpsons)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "修改列表（但并不返回列表）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['homer', 'marge', 'bart', 'lisa']"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# append element to end（一次只能加一个元素）\n",
    "simpsons.append('lisa')\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# append multiple elements to end（一次加多个元素，重复运行重复添加）\n",
    "simpsons.extend(['itchy', 'scratchy'])\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# insert element at index 0 (shifts everything right)（根据位置插入，其他内容右移）\n",
    "simpsons.insert(0, 'maggie')\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['maggie', 'homer', 'marge', 'bart', 'lisa', 'scratchy']"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# search for first instance and remove it（从左往右依次删除）\n",
    "simpsons.remove('itchy')\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'maggie'"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# remove element 0 and return it（删除指定位置的元素，并返回该元素）\n",
    "simpsons.pop(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['marge', 'bart', 'lisa', 'scratchy']"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# remove element 0 (does not return it)（删除指定位置的元素，不返回）\n",
    "del simpsons[0]\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['krusty', 'bart', 'lisa', 'scratchy']"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# replace element 0（替换指定位置的元素）\n",
    "simpsons[0] = 'krusty'\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['krusty', 'bart', 'lisa', 'scratchy', 'ned', 'rod', 'todd']"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# concatenate lists (slower than 'extend' method)（串联两个列表，比 extend 要慢）\n",
    "neighbors = simpsons + ['ned', 'rod', 'todd']\n",
    "neighbors"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在列表中查找元素："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# counts the number of instances（计算实例元素的数量）\n",
    "simpsons.count('lisa')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "'itchy' is not in list",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-55-92dd91e0652f>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# returns index of first instance（返回从左往右第一个实例元素的索引）\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0msimpsons\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'itchy'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m: 'itchy' is not in list"
     ]
    }
   ],
   "source": [
    "# returns index of first instance（返回从左往右第一个实例元素的索引）\n",
    "simpsons.index('itchy')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "列表切片（List slicing）:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'mon'"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# element 0\n",
    "weekdays[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['mon', 'tues', 'wed']"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# elements 0 (inclusive) to 3 (exclusive)（左闭右开：[0,3)，开区间的实质仍然是数集，该数集用符号（a，b）表示，含义一般是在实数a和实数b之间的所有实数，但不包含a和b）\n",
    "weekdays[0:3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['mon', 'tues', 'wed']"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# starting point is implied to be 0（省略不写，表示一直到头）\n",
    "weekdays[:3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['thurs', 'fri']"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# elements 3 (inclusive) through the end（省略不写，表示一直到头）\n",
    "weekdays[3:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'fri'"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# last element（最后一个元素）\n",
    "weekdays[-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['mon', 'wed', 'fri']"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# every 2nd element (step by 2)（从头开始，步长为2的元素）\n",
    "weekdays[::2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['fri', 'thurs', 'wed', 'tues', 'mon']"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# backwards (step by -1)（从尾巴开始，步长为1的元素）\n",
    "weekdays[::-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['fri', 'thurs', 'wed', 'tues', 'mon']"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# alternative method for returning the list backwards（返回颠倒列表的另一种方式）\n",
    "list(reversed(weekdays))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "排序列表（修改列表但并不返回结果列表，因此需要打印出来）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['abcv', 'adc', 'ak']"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "simpsons = ['abcv','adc','ak']\n",
    "simpsons.sort()\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ak', 'adc', 'abcv']"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sort in reverse\n",
    "simpsons.sort(reverse=True)\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ak', 'adc', 'abcv']"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sort by a key（高级用法参考基础课程 list.sort 函数）\n",
    "simpsons.sort(key=len)\n",
    "simpsons"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "返回排序好的列表（但不修改原始列表）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['abcv', 'adc', 'ak']"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted(simpsons)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ak', 'adc', 'abcv']"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted(simpsons, reverse=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ak', 'adc', 'abcv']"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted(simpsons, key=len)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "插入数据到一个已经排序到列表，并依然按照顺序插入："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[10, 20, 30, 40, 50]"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num = [10, 20, 40, 50]\n",
    "from bisect import insort\n",
    "insort(num, 30)\n",
    "num"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对象引用和复制（Object references and copies）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a second reference to the same list\n",
    "same_num = num"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 20, 30, 40, 50]\n",
      "[0, 20, 30, 40, 50]\n"
     ]
    }
   ],
   "source": [
    "# modifies both 'num' and 'same_num'\n",
    "same_num[0] = 0\n",
    "print(num)\n",
    "print(same_num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 20, 30, 40, 50]"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# copy a list (two ways)\n",
    "new_num = num[:]\n",
    "new_num = list(num)\n",
    "new_num"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "检查对象："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num is same_num    # checks whether they are the same object（检查是否是同一对象）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num is new_num\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num == same_num    # checks whether they have the same contents（检查是否是同一内容）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "num == new_num\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Dictionaries \n",
    "> 字典 \n",
    "\n",
    "属性：无序，可迭代，可变，可以包含多种数据类型\n",
    "\n",
    "- 由键值对组成\n",
    "- 键必须唯一，并且可以是字符串，数字或元组\n",
    "- 值可以是任何类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create an empty dictionary (two ways)\n",
    "empty_dict = {}\n",
    "empty_dict = dict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a dictionary (two ways)\n",
    "family = {'dad':'homer', 'mom':'marge', 'size':6}\n",
    "family = dict(dad='homer', mom='marge', size=6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'dad': 'homer', 'mom': 'marge', 'size': 6}\n"
     ]
    }
   ],
   "source": [
    "# convert a list of tuples into a dictionary\n",
    "list_of_tuples = [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]\n",
    "family = dict(list_of_tuples)\n",
    "print(family)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "homer\n",
      "3\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "# examine a dictionary\n",
    "print(family['dad'])       # returns 'homer'\n",
    "print(len(family))         # returns 3\n",
    "print('mom' in family)     # returns True\n",
    "print('marge' in family)   # returns False (only checks keys)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['dad', 'mom', 'size'])\n",
      "dict_values(['homer', 'marge', 6])\n",
      "dict_items([('dad', 'homer'), ('mom', 'marge'), ('size', 6)])\n"
     ]
    }
   ],
   "source": [
    "# returns a list (Python 2) or an iterable view (Python 3)\n",
    "print(family.keys())       # keys: ['dad', 'mom', 'size']\n",
    "print(family.values())     # values: ['homer', 'marge', 6]\n",
    "print(family.items())      # key-value pairs: [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'dad': 'homer', 'mom': 'marge', 'size': 6, 'cat': 'snowball ii'}"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# modify a dictionary (does not return the dictionary)\n",
    "family['cat'] = 'snowball'              # add a new entry\n",
    "family['cat'] = 'snowball ii'           # edit an existing entry\n",
    "family"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'mom': 'marge', 'size': 6, 'kids': ['bart', 'lisa'], 'baby': 'maggie', 'grandpa': 'abe'}\n"
     ]
    }
   ],
   "source": [
    "del family['cat']                       # delete an entry\n",
    "family['kids'] = ['bart', 'lisa']       # dictionary value can be a list\n",
    "family.pop('dad')                       # remove an entry and return the value ('homer')\n",
    "family.update({'baby':'maggie', 'grandpa':'abe'})   # add multiple entries\n",
    "print(family)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'marge'"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# access values more safely with 'get'\n",
    "family['mom']                       # returns 'marge'\n",
    "family.get('mom')                   # equivalent\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'grandma'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-87-20bc8fa94baf>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfamily\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'grandma'\u001b[0m\u001b[0;34m]\u001b[0m                   \u001b[0;31m# throws an error since the key does not exist\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m \u001b[0mfamily\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'grandma'\u001b[0m\u001b[0;34m)\u001b[0m               \u001b[0;31m# returns None instead\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyError\u001b[0m: 'grandma'"
     ]
    }
   ],
   "source": [
    "family['grandma']                   # throws an error since the key does not exist\n",
    "family.get('grandma')               # returns None instead\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'not found'"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "family.get('grandma', 'not found')  # returns 'not found' (the default)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'mom': 'marge', 'size': 6, 'kids': ['bart'], 'baby': 'maggie', 'grandpa': 'abe'}\n"
     ]
    }
   ],
   "source": [
    "# access a list element within a dictionary\n",
    "family['kids'][0]                   # returns 'bart'\n",
    "family['kids'].remove('lisa')       # removes 'lisa'\n",
    "print(family)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'youngest child is maggie'"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# string substitution using a dictionary\n",
    "'youngest child is %(baby)s' % family   # returns 'youngest child is maggie'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Strings\n",
    "> 字符串\n",
    "\n",
    "属性：可迭代，不可变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "# create a string\n",
    "s1 = str(42)         # convert another data type into a string\n",
    "print(s1)\n",
    "print(type(s1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I like you\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s = 'I like you'\n",
    "print(s)\n",
    "print(type(s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "# examine a string\n",
    "print(s[0])                # returns 'I'\n",
    "print(len(s))              # returns 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I like\n",
      "you\n",
      "u\n"
     ]
    }
   ],
   "source": [
    "# string slicing is like list slicing\n",
    "print(s[:6])               # returns 'I like'\n",
    "print(s[7:])               # returns 'you'\n",
    "print(s[-1])               # returns 'u'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "i like you\n",
      "I LIKE YOU\n",
      "True\n",
      "True\n",
      "False\n",
      "2\n",
      "-1\n",
      "I love you\n"
     ]
    }
   ],
   "source": [
    "# basic string methods (does not modify the original string)\n",
    "print(s.lower())           # returns 'i like you'\n",
    "print(s.upper())           # returns 'I LIKE YOU'\n",
    "print(s.startswith('I'))   # returns True\n",
    "print(s.endswith('you'))   # returns True\n",
    "print(s.isdigit())         # returns False (returns True if every character in the string is a digit)\n",
    "print(s.find('like'))      # returns index of first occurrence (2), but doesn't support regex\n",
    "print(s.find('hate'))      # returns -1 since not found\n",
    "print(s.replace('like', 'love'))    # replaces all instances of 'like' with 'love'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['I', 'like', 'you']\n",
      "['I', 'like', 'you']\n",
      "['a', ' an', ' the']\n"
     ]
    }
   ],
   "source": [
    "# split a string into a list of substrings separated by a delimiter\n",
    "print(s.split(' '))        # returns ['I', 'like', 'you']\n",
    "print(s.split())           # equivalent (since space is the default delimiter)\n",
    "s2 = 'a, an, the'\n",
    "print(s2.split(','))       # returns ['a', ' an', ' the']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'larry curly moe'"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# join a list of strings into one string using a delimiter\n",
    "stooges = ['larry', 'curly', 'moe']\n",
    "' '.join(stooges)   # returns 'larry curly moe'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'The meaning of life is 42'"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# concatenate strings（拼接字符串）\n",
    "s3 = 'The meaning of life is'\n",
    "s4 = '42'\n",
    "s3 + ' ' + s4       # returns 'The meaning of life is 42'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'ham and cheese'"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# remove whitespace from start and end of a string（去掉字符串头尾的空格）\n",
    "s5 = '  ham and cheese  '\n",
    "s5.strip()          # returns 'ham and cheese'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'raining cats and dogs'"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# string substitutions: all of these return 'raining cats and dogs'\n",
    "'raining %s and %s' % ('cats', 'dogs')                       # old way\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'raining cats and dogs'"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'raining {} and {}'.format('cats', 'dogs')                   # new way\n",
    "'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs') # named arguments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'pi is 3.14'"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# string formatting（字符串格式）\n",
    "# more examples: https://mkaz.blog/code/python-string-format-cookbook/\n",
    "'pi is {:.2f}'.format(3.14159)      # returns 'pi is 3.14'\n",
    "\n",
    "# f-string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "first line\n",
      "second line\n"
     ]
    }
   ],
   "source": [
    "# normal strings versus raw strings\n",
    "print('first line\\nsecond line')    # normal strings allow for escaped characters\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "first line\\nfirst line\n",
      "first line\\nsecond line\n"
     ]
    }
   ],
   "source": [
    "print(r'first line\\nfirst line')    # raw strings treat backslashes as literal characters\n",
    "print('first line\\\\nsecond line')   # 使用 backslash 也可以"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Conditional Statements\n",
    "> 条件语句"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "positive\n"
     ]
    }
   ],
   "source": [
    "# if statement\n",
    "if x > 0:\n",
    "    print('positive')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "positive\n"
     ]
    }
   ],
   "source": [
    "# if/else statement\n",
    "# x = -5\n",
    "if x > 0:\n",
    "    print('positive')\n",
    "else:\n",
    "    print('zero or negative')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "positive\n"
     ]
    }
   ],
   "source": [
    "# if/elif/else statement\n",
    "if x > 0:\n",
    "    print('positive')\n",
    "elif x == 0:\n",
    "    print('zero')\n",
    "else:\n",
    "    print('negative')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "positive\n"
     ]
    }
   ],
   "source": [
    "# single-line if statement (sometimes discouraged)\n",
    "if x > 0: print('positive')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'positive'"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'\n",
    "'positive' if x > 0 else 'zero or negative'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. For Loops and While Loops\n",
    "> for 循环和 while 循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "APPLE\n",
      "BANANA\n",
      "CHERRY\n"
     ]
    }
   ],
   "source": [
    "# for loop (not the recommended style)\n",
    "fruits = ['apple', 'banana', 'cherry']\n",
    "for i in range(len(fruits)):\n",
    "    print(fruits[i].upper())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "range(0, 8)"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "range(8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "APPLE\n",
      "BANANA\n",
      "CHERRY\n"
     ]
    }
   ],
   "source": [
    "# for loop (recommended style)\n",
    "for fruit in fruits:\n",
    "    print(fruit.upper())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dad homer\n",
      "mom marge\n",
      "size 6\n"
     ]
    }
   ],
   "source": [
    "# iterate through two things at once (using tuple unpacking)\n",
    "family = {'dad':'homer', 'mom':'marge', 'size':6}\n",
    "for key, value in family.items():\n",
    "    print(key, value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 apple\n",
      "1 banana\n",
      "2 cherry\n"
     ]
    }
   ],
   "source": [
    "# use enumerate if you need to access the index value within the loop\n",
    "for index, fruit in enumerate(fruits):\n",
    "    print(index, fruit)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Can't find the banana\n"
     ]
    }
   ],
   "source": [
    "# for/else loop\n",
    "for fruit in fruits:\n",
    "    if fruit == 'juci':\n",
    "        print('Found the banana!')\n",
    "        break    # exit the loop and skip the 'else' block\n",
    "else:\n",
    "    # this block executes ONLY if the for loop completes without hitting 'break'\n",
    "    print(\"Can't find the banana\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This will print 5 times\n",
      "This will print 5 times\n",
      "This will print 5 times\n",
      "This will print 5 times\n",
      "This will print 5 times\n"
     ]
    }
   ],
   "source": [
    "# while loop\n",
    "count = 0\n",
    "while count < 5:\n",
    "    print('This will print 5 times')\n",
    "    count += 1    # equivalent to 'count = count + 1'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10. Tuples\n",
    "> 元组\n",
    "\n",
    "属性：有序，可迭代，不可变，可以包含多种数据类型\n",
    "像列表一样，但它们不会改变大小"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a tuple\n",
    "digits = (0, 1, 'two')          # create a tuple directly\n",
    "digits = tuple([0, 1, 'two'])   # create a tuple from a list\n",
    "zero = (0,)                     # trailing comma is required to indicate it's a tuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# examine a tuple\n",
    "digits[2]           # returns 'two'\n",
    "len(digits)         # returns 3\n",
    "digits.count(0)     # counts the number of instances of that value (1)\n",
    "digits.index(1)     # returns the index of the first instance of that value (1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-119-5ddc06fb8f97>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# elements of a tuple cannot be modified（元组的元素无法修改）\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mdigits\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m2\u001b[0m       \u001b[0;31m# throws an error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "# elements of a tuple cannot be modified（元组的元素无法修改）\n",
    "digits[2] = 2       # throws an error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1, 'two', 3, 4)"
      ]
     },
     "execution_count": 120,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# concatenate tuples（串联元组，每运行一次都会增加一次）\n",
    "digits = digits + (3, 4)\n",
    "digits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3, 4, 3, 4)"
      ]
     },
     "execution_count": 121,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# create a single tuple with elements repeated (also works with lists)\n",
    "# 创建重复元素的单一元组，对于列表同样适用，[1,2] * 2\n",
    "(3, 4) * 2          # returns (3, 4, 3, 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(10, 40), (20, 30), (20, 60)]"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sort a list of tuples\n",
    "tens = [(20, 60), (10, 40), (20, 30)]\n",
    "sorted(tens)        # sorts by first element in tuple, then second element\n",
    "                    # 先以第一个元素排序，再以第二个元素排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "male\n",
      "10\n",
      "simpson\n"
     ]
    }
   ],
   "source": [
    "# tuple unpacking\n",
    "bart = ('male', 10, 'simpson')  # create a tuple\n",
    "(sex, age, surname) = bart      # assign three values at once\n",
    "print(sex)\n",
    "print(age)\n",
    "print(surname)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://pptwinpics.oss-cn-beijing.aliyuncs.com/CDA%E8%AE%B2%E5%B8%88%E6%B0%B4%E5%8D%B0_20200314161940.png)\n",
    "\n",
    "## 11. Sets\n",
    "> 集合\n",
    "\n",
    "属性：无序，可迭代，可变，可以包含多种数据类型\n",
    "由唯一元素（字符串，数字或元组）组成\n",
    "类似于字典，但仅具有键（无值）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create an empty set\n",
    "empty_set = set()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a set\n",
    "languages = {'python', 'r', 'java'}         # create a set directly\n",
    "snakes = set(['cobra', 'viper', 'python'])  # create a set from a list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 126,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# examine a set\n",
    "len(languages)              # returns 3\n",
    "'python' in languages       # returns True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'cobra', 'viper'}"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# set operations\n",
    "languages & snakes          # returns intersection: {'python'}\n",
    "languages | snakes          # returns union: {'cobra', 'r', 'java', 'viper', 'python'}\n",
    "languages - snakes          # returns set difference: {'r', 'java'}\n",
    "snakes - languages          # returns set difference: {'cobra', 'viper'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'c'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-128-5452b3be7924>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0mlanguages\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m          \u001b[0;31m# try to add an existing element (ignored, no error)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0mlanguages\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mremove\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'java'\u001b[0m\u001b[0;34m)\u001b[0m    \u001b[0;31m# remove an element\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mlanguages\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mremove\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'c'\u001b[0m\u001b[0;34m)\u001b[0m       \u001b[0;31m# try to remove a non-existing element (throws an error)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      6\u001b[0m \u001b[0mlanguages\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdiscard\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'c'\u001b[0m\u001b[0;34m)\u001b[0m      \u001b[0;31m# remove an element if present, but ignored otherwise\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[0mlanguages\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m             \u001b[0;31m# remove and return an arbitrary element\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyError\u001b[0m: 'c'"
     ]
    }
   ],
   "source": [
    "# modify a set (does not return the set)\n",
    "languages.add('sql')        # add a new element\n",
    "languages.add('r')          # try to add an existing element (ignored, no error)\n",
    "languages.remove('java')    # remove an element\n",
    "languages.remove('c')       # try to remove a non-existing element (throws an error)\n",
    "languages.discard('c')      # remove an element if present, but ignored otherwise\n",
    "languages.pop()             # remove and return an arbitrary element\n",
    "languages.clear()           # remove all elements\n",
    "languages.update(['go', 'spark'])  # add multiple elements (can also pass a set)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 1, 2, 9]"
      ]
     },
     "execution_count": 129,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# get a sorted list of unique elements from a list\n",
    "sorted(set([9, 0, 2, 1, 0]))    # returns [0, 1, 2, 9]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 12. Defining Functions\n",
    "> 定义函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define a function with no arguments and no return values\n",
    "def print_text():\n",
    "    print('this is text')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "this is text\n"
     ]
    }
   ],
   "source": [
    "# call the function\n",
    "print_text()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define a function with one argument and no return values\n",
    "def print_this(x):\n",
    "    print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "# call the function\n",
    "print_this(3)       # prints 3\n",
    "n = print_this(3)   # prints 3, but doesn't assign 3 to n\n",
    "                    #   because the function has no return statement"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 134,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define a function with one argument and one return value\n",
    "def square_this(x):\n",
    "    return x**2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "metadata": {},
   "outputs": [],
   "source": [
    "# include an optional docstring to describe the effect of a function\n",
    "def square_this(x):\n",
    "    \"\"\"Return the square of a number.\"\"\"\n",
    "    return x**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 136,
   "metadata": {},
   "outputs": [],
   "source": [
    "# call the function\n",
    "square_this(3)          # prints 9\n",
    "var = square_this(3)    # assigns 9 to var, but does not print 9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define a function with two 'positional arguments' (no default values) and\n",
    "# one 'keyword argument' (has a default value)\n",
    "def calc(a, b, op='add'):\n",
    "    if op == 'add':\n",
    "        return a + b\n",
    "    elif op == 'sub':\n",
    "        return a - b\n",
    "    else:\n",
    "        print('valid operations are add and sub')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "valid operations are add and sub\n"
     ]
    }
   ],
   "source": [
    "# call the function\n",
    "calc(10, 4, op='add')   # returns 14\n",
    "calc(10, 4, 'add')      # also returns 14: unnamed arguments are inferred by position\n",
    "calc(10, 4)             # also returns 14: default for 'op' is 'add'\n",
    "calc(10, 4, 'sub')      # returns 6\n",
    "calc(10, 4, 'div')      # prints 'valid operations are add and sub'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [],
   "source": [
    "# use 'pass' as a placeholder if you haven't written the function body\n",
    "def stub():\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "metadata": {},
   "outputs": [],
   "source": [
    "# return two values from a single function\n",
    "def min_max(nums):\n",
    "    return min(nums), max(nums)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [],
   "source": [
    "# return values can be assigned to a single variable as a tuple\n",
    "nums = [1, 2, 3]\n",
    "min_max_num = min_max(nums)         # min_max_num = (1, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {},
   "outputs": [],
   "source": [
    "# return values can be assigned into multiple variables using tuple unpacking\n",
    "min_num, max_num = min_max(nums)    # min_num = 1, max_num = 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 13. Anonymous (LAMBDA) Functions\n",
    "> 匿名函数（lambda）\n",
    "\n",
    "主要用于临时定义一个功能以供另一个功能使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define a function the \"usual\" way\n",
    "def squared(x):\n",
    "    return x**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define an identical function using lambda\n",
    "squared = lambda x: x**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['marge', 'homer', 'bart']"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sort a list of strings by the last letter (without using lambda)\n",
    "simpsons = ['homer', 'marge', 'bart']\n",
    "def last_letter(word):\n",
    "    return word[-1]\n",
    "sorted(simpsons, key=last_letter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['marge', 'homer', 'bart']"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sort a list of strings by the last letter (using lambda)\n",
    "sorted(simpsons, key=lambda word: word[-1])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 14. Comprehensions\n",
    "> 推导式，解析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 8, 27, 64, 125]\n"
     ]
    }
   ],
   "source": [
    "# for loop to create a list of cubes（for 循环创造一个列表）\n",
    "nums = [1, 2, 3, 4, 5]\n",
    "cubes = []\n",
    "for num in nums:\n",
    "    cubes.append(num**3)\n",
    "print(cubes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 8, 27, 64, 125]\n"
     ]
    }
   ],
   "source": [
    "# equivalent list comprehension（如果写成列表解析式就是这样）\n",
    "cubes = [num**3 for num in nums]    # [1, 8, 27, 64, 125]\n",
    "print(cubes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[8, 64]\n"
     ]
    }
   ],
   "source": [
    "# for loop to create a list of cubes of even numbers(偶数)\n",
    "cubes_of_even = []\n",
    "for num in nums:\n",
    "    if num % 2 == 0:  # 整除，取余数是0\n",
    "        cubes_of_even.append(num**3)\n",
    "print(cubes_of_even)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [],
   "source": [
    "# equivalent list comprehension\n",
    "# syntax: [expression for variable in iterable if condition]\n",
    "cubes_of_even = [num**3 for num in nums if num % 2 == 0]    # [8, 64]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "metadata": {},
   "outputs": [],
   "source": [
    "# for loop to cube even numbers and square odd numbers\n",
    "cubes_and_squares = []\n",
    "for num in nums:\n",
    "    if num % 2 == 0:\n",
    "        cubes_and_squares.append(num**3)\n",
    "    else:\n",
    "        cubes_and_squares.append(num**2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [],
   "source": [
    "# equivalent list comprehension (using a ternary expression)\n",
    "# syntax: [true_condition if condition else false_condition for variable in iterable]\n",
    "cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]    # [1, 8, 9, 64, 25]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [],
   "source": [
    "# for loop to flatten a 2d-matrix\n",
    "matrix = [[1, 2], [3, 4]]\n",
    "items = []\n",
    "for row in matrix:\n",
    "    for item in row:\n",
    "        items.append(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {},
   "outputs": [],
   "source": [
    "# equivalent list comprehension\n",
    "items = [item for row in matrix\n",
    "              for item in row]      # [1, 2, 3, 4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "metadata": {},
   "outputs": [],
   "source": [
    "# set comprehension\n",
    "fruits = ['apple', 'banana', 'cherry']\n",
    "unique_lengths = {len(fruit) for fruit in fruits}   # {5, 6}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {},
   "outputs": [],
   "source": [
    "# dictionary comprehension\n",
    "fruit_lengths = {fruit:len(fruit) for fruit in fruits}              # {'apple': 5, 'banana': 6, 'cherry': 6}\n",
    "fruit_indices = {fruit:index for index, fruit in enumerate(fruits)} # {'apple': 0, 'banana': 1, 'cherry': 2}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 15. Map and Filter\n",
    "> "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<map at 0x11d3a4e50>"
      ]
     },
     "execution_count": 157,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 'map' applies a function to every element of a sequence\n",
    "# ...and returns a list (Python 2) or iterator (Python 3)\n",
    "simpsons = ['homer', 'marge', 'bart']\n",
    "map(len, simpsons)                      # returns [5, 5, 4]\n",
    "map(lambda word: word[-1], simpsons)    # returns ['r', 'e', 't']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['r', 'e', 't']"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# equivalent list comprehensions\n",
    "[len(word) for word in simpsons]\n",
    "[word[-1] for word in simpsons]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<filter at 0x11d3af750>"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 'filter' returns a list (Python 2) or iterator (Python 3) containing\n",
    "# ...the elements from a sequence for which a condition is True\n",
    "nums = range(5)\n",
    "filter(lambda x: x % 2 == 0, nums)      # returns [0, 2, 4]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 4]"
      ]
     },
     "execution_count": 160,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# equivalent list comprehension\n",
    "[num for num in nums if num % 2 == 0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[[返回顶部]](#目录)\n",
    "![](https://pptwinpics.oss-cn-beijing.aliyuncs.com/CDA%E8%AE%B2%E5%B8%88%E6%B0%B4%E5%8D%B0_20200314161940.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "212.797px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
